package com.brave.user.service;

import com.aliyun.oss.OSS;
import com.brave.base.BaseService;
import com.brave.base.MD5Kit;
import com.brave.file.controller.QRCodeGen;
import com.brave.user.dto.RedisUserInfo;
import com.brave.user.entity.MCUserBaseInfo;
import com.brave.user.repository.MCUserBaseInfoRepository;
import com.brave.user.repository.MCUserSignDetailRepository;
import com.brave.utils.AliOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class UserQueryService extends BaseService
{
    @Autowired
    private MCUserBaseInfoRepository userBaseInfoRepository;
    @Autowired
    private OSS ossClientBuilder;
    @Value("${invite.user.url.prefix}")
    private String qrCodeContent;
    @Value("${upload.file.root.path}")
    private String rootPath;
    @Autowired
    private QRCodeGen qrCodeGen;
    @Autowired
    private MCUserSignDetailRepository userSignDetailRepository;
    
    
    /**
     * 2019年8月23日 15:13:30
     * 查询手机号码是否被占用
     * @param phone
     * @return
     */
    public String findPhoneExist(String phone)
    {
        MCUserBaseInfo userInfo = userBaseInfoRepository.findFirstByPhone(phone);
        if(null != userInfo && 0 < userInfo.getId())
        {
            return paramException("手机号码被占用");
        }else
        {
            return success("手机号未被占用");
        }
    }


    /**
     * 2019年10月11日 00:15:01
     * 查询用户的详细信息
     * @param redisUserInfo
     * @return
     */
    public String findUserInfo(RedisUserInfo redisUserInfo)
    {
        Optional<MCUserBaseInfo> userOptional = userBaseInfoRepository.findById(redisUserInfo.getId());
        if(userOptional.isPresent())
        {
            MCUserBaseInfo userInfo = userOptional.get();
            return success(userInfo);
        }
        return success();
    }
    
    

    /**
     * 2019年10月15日 16:45:09
     * 查询我的二维码
     * @param redisUserInfo
     * @return
     */
    public String findInviteQRCode(RedisUserInfo redisUserInfo)
    {
        Optional<MCUserBaseInfo> userOptional = userBaseInfoRepository.findById(redisUserInfo.getId());
        if(userOptional.isPresent())
        {
            Map<String, Object> resultMap = new HashMap<>(2);
            MCUserBaseInfo userInfo = userOptional.get();
            //二维码之前已经存在的情况
            if(null != userInfo.getQrcodeUrl() && !"".equals(userInfo.getQrcodeUrl()))
            {
                resultMap.put("qrCodeUrl", userInfo.getQrcodeUrl());
            }else
            {
                //二维码之前未设置的情况
                try
                {
                    String content = String.format("%s%s", qrCodeContent, MD5Kit.MD5Encode(String.format("%d", redisUserInfo.getId())));
                    BufferedImage image = qrCodeGen.drawLogoQRCode(content);
                    File folder = new File(rootPath + "QRCode" + File.separator);
                    if(!folder.exists())
                    {
                        folder.mkdirs();
                    }
                    File qrCodeFile = new File(rootPath + "QRCode" + File.separator + redisUserInfo.getId() + ".png");
                    if(qrCodeFile.exists())
                    {
                        qrCodeFile.delete();
                    }
                    ImageIO.write(image, "png", qrCodeFile.getCanonicalFile());
                    InputStream is = new FileInputStream(qrCodeFile);
                    ossClientBuilder.putObject(AliOSSConfig.ALI_OSS_BUCKET_NAME, qrCodeFile.getName(), is);
                    userInfo.setQrcodeUrl(String.format("%s%s", "https://has-free-bucket.oss-cn-shenzhen.aliyuncs.com/", qrCodeFile.getName()));
                    userBaseInfoRepository.save(userInfo);
//                    ossClientBuilder.shutdown();
                    is.close();
                }catch(IOException ioe)
                {
                    ioe.printStackTrace();
                }
                resultMap.put("qrCodeUrl", userInfo.getQrcodeUrl());
            }
            return success(resultMap);
        }
        return success();
    }


    /**
     * 2019年10月17日 09:01:17
     * 获取个人签到明细
     * @param redisUserInfo
     * @return
     */
    public String findUserSignDetail(RedisUserInfo redisUserInfo)
    {
        //当前年份
        Calendar calendar = Calendar.getInstance();
        
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        StringBuilder querySQL = new StringBuilder();
        querySQL.append("SELECT ");
        querySQL.append(" si.sort day,  ");
        querySQL.append(" CASE WHEN sd.id is null THEN 0 ");
        querySQL.append("  ELSE 1 END mark ");
        querySQL.append("FROM mc_user_sign_info si LEFT JOIN (SELECT * FROM mc_user_sign_detail WHERE user_id = ");
        querySQL.append(redisUserInfo.getId());
        querySQL.append(" ) sd ON si.id = sd.sign_id  ");
        querySQL.append("WHERE year = ");
        querySQL.append(year);
        querySQL.append(" AND month = ");
        querySQL.append(month);
        querySQL.append(" ORDER BY si.sort ASC");

        List<Map<String, Object>> resultList = userSignDetailRepository.findList(querySQL.toString());
        return success(resultList);
    }
    
    
}
